#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import shutil
import zipfile
import sys


def un_zip(file_path):
    f = zipfile.ZipFile(file_path, 'r')
    (path, filename) = os.path.split(file_path)
    des_dir = str(filename).split('.')[0]
    for file in f.namelist():
        f.extract(file, des_dir)
    return des_dir


def get_zip(files_dir):
    zip_file_name = files_dir.split('\\')[-1] + '-removed_password.zip'
    f = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
    startdir = files_dir
    os.chdir(startdir)
    for dirpath, dirnames, filenames in os.walk(".", topdown=False):
        for filename in filenames:
            f.write(os.path.join(dirpath, filename))
    f.close()
    return zip_file_name


# 将每个sheet.xml中'sheetProtection' 替换成其他无意义内容，如'qwe'
def remove_node(file_path):
    fileForReading = open(file_path, 'r', encoding='utf-8')
    xmlString = fileForReading.read()
    fileForReading.close()
    xmlString = xmlString.replace('sheetProtection', 'qwe')
    fileForWriting = open(file_path, 'w', encoding='utf-8')
    fileForWriting.write(xmlString)
    fileForWriting.close()


# 用于更改文件后缀名
def replace_suffix(file_path, suffix):
    new_path = ''
    for i in range(1, len(file_path)):
        if file_path[-i] == '.':  # 找到后缀初始点
            new_path = file_path.replace(file_path[-i + 1:], suffix)  # 替换后缀
            break
    os.rename(file_path, new_path)
    return new_path


# 用于遍历文件夹，获取所有xml文件
def walkFile(rootDir):
    list_dirs = os.walk(rootDir)
    file_list = []
    for root, dirs, files in list_dirs:
        for f in files:
            if f.split('.')[-1] == 'xml':
                file_list.append(os.path.join(root, f))
    return file_list


if __name__ == '__main__':
    excel_file_name = sys.argv[1:][0]
    # excel_file_name = 'test.xlsx'
    # 待破解密码的excel文件路径
    excel_file_path = os.getcwd() + '\\' + excel_file_name
    # 将待破解密码的excel文件后缀名改为.zip
    new_path = replace_suffix(excel_file_path, 'zip')
    # 解压缩上一步的zip文件
    des_dir = un_zip(new_path)
    # 解压缩后，把后缀名再次改回.xlsx
    replace_suffix(new_path, 'xlsx')
    # 获取sheet.xml文件存放的路径
    dir_path = os.getcwd() + '\\' + des_dir + r'\xl\worksheets'
    # 遍历sheet.xml文件存放路径，获取所有sheet.xml文件
    file_list = walkFile(dir_path)
    # 遍历所有sheet.xml文件 修改 'sheetProtection'节点
    for i in file_list:
        remove_node(i)
    # 切换当前路径至解压后文件的文件夹
    zip_files_dir = os.getcwd() + '\\' + des_dir
    # 压缩该文件夹
    zip_file_name = get_zip(zip_files_dir)
    # 切换当前路径至上一级
    pwd = os.path.abspath(os.path.join(os.getcwd(), ".."))
    os.chdir(pwd)
    # 将压缩文件的后缀名改为.xlsx，完成密码破解
    new_path = replace_suffix(os.getcwd() + '\\' + zip_file_name, 'xlsx')
    # 删除临时生成的文件夹
    shutil.rmtree(zip_files_dir)


